package controllers

import (
	"encoding/json"
	"stock_app/logic"
	"stock_app/models"
	"strconv"

	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

// HandleJobSave 保存Job任务的函数
func HandleJobSave(c *gin.Context) {
	//1.获取参数和参数校验
	var job models.Job
	postJob := c.PostForm("job")
	// 反序列化job
	if err := json.Unmarshal([]byte(postJob), &job); err != nil {
		zap.L().Error("HandleJobSave failed", zap.Error(err))
		ResponseError(c, CodeInvalidParam)
		return
	}
	//2.业务处理
	// fmt.Println("打印创建的Job")
	// fmt.Println(job)
	oldJob, err := logic.SaveJob(&job)
	if err != nil {
		ResponseError(c, CodeServerBusy)
		return
	}
	//3.返回响应
	ResponseSuccess(c, oldJob)
}

// HandleJobDelete 删除Job任务
func HandleJobDelete(c *gin.Context) {
	//1.获取参数和参数校验
	name := c.PostForm("name")
	if name == "" {
		ResponseError(c, CodeInvalidParam)
		return
	}
	//2.业务处理
	oldJob, err := logic.DeleteJob(name)
	if err != nil {
		ResponseError(c, CodeServerBusy)
		return
	}
	//3.放回响应
	ResponseSuccess(c, oldJob)
}

// HandleJobList 列举所有crontab任务
func HandleJobList(c *gin.Context) {
	data, err := logic.GetJobList()
	if err != nil {
		zap.L().Error("logic.GetJobList failed", zap.Error(err))
		ResponseError(c, CodeServerBusy)
		return
	}
	ResponseSuccess(c, data)
}

// HandleJobKill 杀死crontab任务
func HandleJobKill(c *gin.Context) {
	//1.获取参数和参数校验
	name := c.PostForm("name")
	if name == "" {
		ResponseError(c, CodeInvalidParam)
		return
	}
	//2.业务处理
	err := logic.KillJob(name)
	if err != nil {
		ResponseError(c, CodeServerBusy)
		return
	}
	//3.返回响应
	ResponseSuccess(c, "")
}

// HandleJobLog 列举所有crontab任务的日志
func HandleJobLog(c *gin.Context) {
	//1.获取参数和参数校验
	name := c.Query("name")
	skipParam := c.Query("skip")
	limitParam := c.Query("limit")
	skip, err := strconv.ParseInt(skipParam, 10, 64)
	if err != nil {
		skip = 0
	}
	limit, err := strconv.ParseInt(limitParam, 10, 64)
	if err != nil {
		limit = 20
	}
	//2.业务处理
	data, err := logic.ListLog(name, skip, limit)
	if err != nil {
		zap.L().Error("logic.ListLog failed", zap.Error(err))
		ResponseError(c, CodeServerBusy)
		return
	}
	//3.放回响应
	ResponseSuccess(c, data)
}

// HandleWorkerList 列举所有work节点
func HandleWorkerList(c *gin.Context) {
	data, err := logic.GetWorkList()
	if err != nil {
		zap.L().Error("logic.GetJobList failed", zap.Error(err))
		ResponseError(c, CodeServerBusy)
		return
	}
	ResponseSuccess(c, data)
}
